<template>
  <div class="process-maintenance">
    <div class="page-header">
      <h2>工序维护</h2>
      <p>管理和维护生产工序相关信息</p>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="action-bar">
      <div class="search-section" v-show="showSearch">
        <el-input
          v-model="queryForm.processmaintenanceEncode"
          placeholder="请输入编码"
          class="search-input"
          clearable
        />
        <el-input
          v-model="queryForm.processmaintenanceName"
          placeholder="请输入名称"
          class="search-input"
          clearable
        />
        <el-select v-model="queryForm.processmaintenanceType" placeholder="请选择类型" clearable style="width: 180px">
          <el-option v-for="type in PROCESS_TYPES" :key="type.value" :label="type.label" :value="type.value" />
        </el-select>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 列表工具栏，与表格同区域1 -->
    <div class="list-toolbar">
      <div class="button-section">
        <el-button 
          type="info" 
          class="allocate-btn"
          :disabled="isAllocateBtnDisabled"
          @click="handleAllocateAttributes"
        >
          <el-icon><Setting /></el-icon>
          分配属性
        </el-button>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <el-button 
          type="success" 
          :disabled="selectedRows.length === 0"
          @click="handleExport"
        >
          <el-icon><Download /></el-icon>
          导出
        </el-button>
        <el-button type="text" class="icon-btn" @click="toggleSearch" title="显示/隐藏查询">
          <el-icon><Search /></el-icon>
        </el-button>
        <el-button type="text" class="icon-btn" title="刷新" @click="loadData">
          <el-icon><Refresh /></el-icon>
        </el-button>
        <el-button type="text" class="icon-btn" title="全屏">
          <el-icon><FullScreen /></el-icon>
        </el-button>
        <el-button type="text" class="icon-btn" title="设置">
          <el-icon><Setting /></el-icon>
        </el-button>
        <el-button type="text" class="icon-btn" title="帮助">
          <el-icon><QuestionFilled /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        :fit="true"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" />
        <el-table-column prop="serialNumber" label="序号" />
        <el-table-column prop="processCode" label="编码" show-overflow-tooltip>
          <template #header>
            <span>编码</span>
          </template>
        </el-table-column>
        <el-table-column prop="processName" label="名称" show-overflow-tooltip>
          <template #header>
            <span>名称</span>
          </template>
        </el-table-column>
        <el-table-column prop="processType" label="类型">
          <template #header>
            <span>类型</span>
          </template>
          <template #default="scope">
            <el-tag
              :type="getTypeTagType(scope.row.processType)"
              size="small"
            >
              {{ scope.row.processType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="workReportMode" label="报工模式">
          <template #default="scope">
            <el-tag
              :type="getModeTagType(scope.row.workReportMode)"
              size="small"
            >
              {{ scope.row.workReportMode }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip>
          <template #header>
            <span>描述</span>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" show-overflow-tooltip>
          <template #header>
            <span>创建人</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" sortable>
          <template #header>
            <span>创建时间</span>
            <el-icon class="sort-icon"><Sort /></el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" sortable>
          <template #header>
            <span>更新时间</span>
            <el-icon class="sort-icon"><Sort /></el-icon>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <div class="pagination-left">
        <span>共{{ total }}条数据</span>
      </div>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <div class="pagination-right">
        <el-select v-model="pageSize" @change="handleSizeChange">
          <el-option
            v-for="size in [10, 20, 50, 100]"
            :key="size"
            :label="`${size}条/页`"
            :value="size"
          />
        </el-select>
        <span>跳至</span>
        <el-input
          v-model="jumpPage"
          class="jump-input"
          size="small"
          @keyup.enter="handleJumpPage"
        />
        <span>页</span>
        <el-button size="small" @click="handleJumpPage">前往</el-button>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="60%"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工序编码" prop="processCode">
              <el-input 
                v-model="formData.processCode" 
                placeholder="请输入工序编码" 
                @click="handleCodeClick"
                readonly
                class="clickable-input"
              >
                <template #suffix>
                  <el-icon class="code-icon">
                    <Setting />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工序名称" prop="processName">
              <el-input v-model="formData.processName" placeholder="请输入工序名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工序类型" prop="processType">
              <el-select v-model="formData.processType" placeholder="请选择工序类型" style="width: 100%">
                <el-option
                  v-for="type in PROCESS_TYPES"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报工模式" prop="workReportMode">
              <el-select v-model="formData.workReportMode" placeholder="请选择报工模式" style="width: 100%">
                <el-option
                  v-for="mode in WORK_REPORT_MODES"
                  :key="mode.value"
                  :label="mode.label"
                  :value="mode.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="工序描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入工序描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配属性对话框 -->
    <el-dialog
      v-model="allocateDialogVisible"
      title="分配属性-工序"
      width="1000px"
      :before-close="handleAllocateDialogClose"
    >
      <div class="allocate-dialog-content">
        <div class="transfer-container">
          <!-- 左侧列表 -->
          <div class="left-list">
            <div class="list-header">
              <span>{{ filteredLeftTableData.length }}项</span>
              <el-button 
                type="primary" 
                size="small"
                @click="handleAddAttribute"
              >
                <el-icon><Plus /></el-icon>
                添加
              </el-button>
            </div>
            <div class="search-box">
              <el-input
                v-model="leftSearchKeyword"
                placeholder="请输入编码搜索"
                size="small"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            <div class="table-wrapper">
              <el-table
                :data="filteredLeftTableData"
                height="200"
                size="small"
                @selection-change="handleLeftSelectionChange"
              >
                <el-table-column type="selection" width="50" />
                <el-table-column prop="code" label="编码" width="80" />
                <el-table-column prop="name" label="名称" width="80" />
                <el-table-column prop="remark" label="备注" />
              </el-table>
            </div>
            <div class="pagination-wrapper">
              <el-pagination
                :current-page="1"
                :page-size="10"
                :total="filteredLeftTableData.length"
                layout="prev, pager, next"
                size="small"
              />
            </div>
          </div>

          <!-- 中间按钮 -->
          <div class="middle-buttons">
            <el-button 
              type="primary" 
              size="small"
              :disabled="leftSelectedRows.length === 0"
              @click="handleMoveToRight"
            >
              <el-icon><ArrowRight /></el-icon>
            </el-button>
            <el-button 
              type="primary" 
              size="small"
              :disabled="rightSelectedRows.length === 0"
              @click="handleMoveToLeft"
            >
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
          </div>

          <!-- 右侧列表 -->
          <div class="right-list">
            <div class="list-header">
              <span>{{ filteredRightTableData.length }}项</span>
            </div>
            <div class="search-box">
              <el-input
                v-model="rightSearchKeyword"
                placeholder="请输入编码搜索"
                size="small"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            <div class="table-wrapper">
              <el-table
                :data="filteredRightTableData"
                height="200"
                size="small"
                @selection-change="handleRightSelectionChange"
              >
                <el-table-column type="selection" width="50" />
                <el-table-column label="值" width="120">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.value"
                      size="small"
                      placeholder="请输入值"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="dataType" label="数据类型" width="80" />
                <el-table-column prop="code" label="编码" width="60" />
                <el-table-column prop="name" label="名称" width="60" />
                <el-table-column prop="remark" label="备注" />
              </el-table>
            </div>
            <div class="pagination-wrapper">
              <el-pagination
                :current-page="1"
                :page-size="10"
                :total="filteredRightTableData.length"
                layout="prev, pager, next"
                size="small"
              />
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="allocateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAllocateConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加属性对话框 -->
    <el-dialog
      v-model="addAttributeDialogVisible"
      :title="`添加属性 - 工序ID: ${addAttributeFormData.id || '未设置'}`"
      width="500px"
      :before-close="handleAddAttributeDialogClose"
    >
      <el-form
        ref="addAttributeFormRef"
        :model="addAttributeFormData"
        :rules="addAttributeFormRules"
        label-width="120px"
      >
        <el-form-item label="属性值" prop="assignattributesOnevalue">
          <el-input 
            v-model="addAttributeFormData.assignattributesOnevalue" 
            placeholder="请输入属性值" 
          />
        </el-form-item>
        
        <el-form-item label="属性编码" prop="assignattributesOneEncode">
          <el-input 
            v-model="addAttributeFormData.assignattributesOneEncode" 
            placeholder="请输入属性编码" 
            @click="handleAttributeCodeClick"
            readonly
            class="clickable-input"
          >
            <template #suffix>
              <el-icon class="code-icon">
                <Setting />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="属性名称" prop="assignattributesOneNamd">
          <el-input 
            v-model="addAttributeFormData.assignattributesOneNamd" 
            placeholder="请输入属性名称" 
          />
        </el-form-item>
        
        <el-form-item label="备注" prop="assignattributesOneRemark">
          <el-input
            v-model="addAttributeFormData.assignattributesOneRemark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addAttributeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddAttributeSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编码规则生成对话框 -->
    <el-dialog
      v-model="codeRuleDialogVisible"
      title="单据编码(新建)"
      width="800px"
      :before-close="handleCodeRuleDialogClose"
    >
      <el-form
        ref="codeRuleFormRef"
        :model="codeRuleFormData"
        :rules="codeRuleFormRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="业务名称" prop="businessName">
              <el-select 
                v-model="codeRuleFormData.businessName" 
                placeholder="请选择业务名称"
                style="width: 100%"
              >
                <el-option label="用户管理" value="用户管理" />
                <el-option label="工序维护" value="工序维护" />
                <el-option label="产品管理" value="产品管理" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规则名称" prop="ruleName">
              <el-input 
                v-model="codeRuleFormData.ruleName" 
                placeholder="请输入规则名称" 
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单据字段" prop="documentField">
              <el-select 
                v-model="codeRuleFormData.documentField" 
                placeholder="请选择单据字段"
                style="width: 100%"
              >
                <el-option label="账号" value="账号" />
                <el-option label="工序编码" value="工序编码" />
                <el-option label="产品编码" value="产品编码" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日期排序字段" prop="dateField">
              <el-select 
                v-model="codeRuleFormData.dateField" 
                placeholder="请选择日期排序字段"
                style="width: 100%"
              >
                <el-option label="注册时间" value="注册时间" />
                <el-option label="创建时间" value="创建时间" />
                <el-option label="更新时间" value="更新时间" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="前缀" prop="prefix">
              <el-input 
                v-model="codeRuleFormData.prefix" 
                placeholder="请输入前缀" 
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规则类型" prop="ruleType">
              <div class="rule-type-radio">
                <el-radio-group v-model="codeRuleFormData.ruleType">
                  <el-radio label="年">年</el-radio>
                  <el-radio label="年月">年月</el-radio>
                  <el-radio label="年月日">年月日</el-radio>
                  <el-radio label="无">无</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="编号位数" prop="numberLength">
              <el-input-number 
                v-model="codeRuleFormData.numberLength" 
                :min="1" 
                :max="10" 
                style="width: 100%" 
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="增长类型" prop="incrementType">
              <el-select 
                v-model="codeRuleFormData.incrementType" 
                placeholder="请选择增长类型"
                style="width: 100%"
              >
                <el-option label="编号每日从1开始自增" value="编号每日从1开始自增" />
                <el-option label="编号每月从1开始自增" value="编号每月从1开始自增" />
                <el-option label="编号每年从1开始自增" value="编号每年从1开始自增" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="连接符号" prop="connector">
          <el-input 
            v-model="codeRuleFormData.connector" 
            placeholder="请输入连接符号" 
            style="width: 200px"
          />
        </el-form-item>

        <div class="code-preview-section">
          <h4>编码预览</h4>
          <div class="preview-code">
            {{ generatePreviewCode() }}
          </div>
        </div>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCodeRuleCancel">关闭</el-button>
          <el-button type="primary" @click="handleCodeRuleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 属性编码规则生成对话框 -->
    <el-dialog
      v-model="attributeCodeRuleDialogVisible"
      title="单据编码(新建) - 属性编码"
      width="800px"
      :before-close="handleAttributeCodeRuleDialogClose"
    >
      <el-form
        ref="attributeCodeRuleFormRef"
        :model="attributeCodeRuleFormData"
        :rules="attributeCodeRuleFormRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="业务名称" prop="businessName">
              <el-select 
                v-model="attributeCodeRuleFormData.businessName" 
                placeholder="请选择业务名称"
                style="width: 100%"
              >
                <el-option label="属性管理" value="属性管理" />
                <el-option label="工序维护" value="工序维护" />
                <el-option label="产品管理" value="产品管理" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规则名称" prop="ruleName">
              <el-input 
                v-model="attributeCodeRuleFormData.ruleName" 
                placeholder="请输入规则名称" 
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单据字段" prop="documentField">
              <el-select 
                v-model="attributeCodeRuleFormData.documentField" 
                placeholder="请选择单据字段"
                style="width: 100%"
              >
                <el-option label="属性编码" value="属性编码" />
                <el-option label="工序编码" value="工序编码" />
                <el-option label="产品编码" value="产品编码" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日期排序字段" prop="dateField">
              <el-select 
                v-model="attributeCodeRuleFormData.dateField" 
                placeholder="请选择日期排序字段"
                style="width: 100%"
              >
                <el-option label="注册时间" value="注册时间" />
                <el-option label="创建时间" value="创建时间" />
                <el-option label="更新时间" value="更新时间" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="前缀" prop="prefix">
              <el-input 
                v-model="attributeCodeRuleFormData.prefix" 
                placeholder="请输入前缀" 
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规则类型" prop="ruleType">
              <div class="rule-type-radio">
                <el-radio-group v-model="attributeCodeRuleFormData.ruleType">
                  <el-radio label="年">年</el-radio>
                  <el-radio label="年月">年月</el-radio>
                  <el-radio label="年月日">年月日</el-radio>
                  <el-radio label="无">无</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="编号位数" prop="numberLength">
              <el-input-number 
                v-model="attributeCodeRuleFormData.numberLength" 
                :min="1" 
                :max="10" 
                style="width: 100%" 
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="增长类型" prop="incrementType">
              <el-select 
                v-model="attributeCodeRuleFormData.incrementType" 
                placeholder="请选择增长类型"
                style="width: 100%"
              >
                <el-option label="编号每日从1开始自增" value="编号每日从1开始自增" />
                <el-option label="编号每月从1开始自增" value="编号每月从1开始自增" />
                <el-option label="编号每年从1开始自增" value="编号每年从1开始自增" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="连接符号" prop="connector">
          <el-input 
            v-model="attributeCodeRuleFormData.connector" 
            placeholder="请输入连接符号" 
            style="width: 200px"
          />
        </el-form-item>

        <div class="code-preview-section">
          <h4>编码预览</h4>
          <div class="preview-code">
            {{ generateAttributePreviewCode() }}
          </div>
        </div>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleAttributeCodeRuleCancel">关闭</el-button>
          <el-button type="primary" @click="handleAttributeCodeRuleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Plus, Upload, Download, Folder, Setting, Refresh, FullScreen, QuestionFilled, Sort, ArrowRight, ArrowLeft } from '@element-plus/icons-vue'
import type { ProcessInfo, ProcessFormData } from '@/types/process'
import { PROCESS_TYPES, WORK_REPORT_MODES } from '@/types/process'
import { APIs } from '@/Http/http'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

// 响应式数据
const searchKeyword = ref('')
const tableData = ref<ProcessInfo[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('新增工序')
const formRef = ref<FormInstance>()
const jumpPage = ref('')
const showSearch = ref(false)
const isEditMode = ref(false)  // 编辑模式标记
const editingId = ref<number | null>(null)  // 正在编辑的记录ID

// 选择状态管理
const selectedRows = ref<ProcessInfo[]>([])
const isAllocateBtnDisabled = ref(true)
const allocateDialogVisible = ref(false)

// 分配属性数据
const leftTableData = ref([])
const rightTableData = ref([])

// 选择状态管理
const leftSelectedRows = ref<any[]>([])
const rightSelectedRows = ref<any[]>([])

// 搜索关键词
const leftSearchKeyword = ref('')
const rightSearchKeyword = ref('')

// 声明qw变量
var qw: number = 0
console.log('qw:', qw)
// 添加属性对话框相关数据
const addAttributeDialogVisible = ref(false)
const addAttributeFormRef = ref<FormInstance>()
const addAttributeFormData = reactive({
  assignattributesOnevalue: '',
  assignattributesOneEncode: '',
  assignattributesOneNamd: '',
  assignattributesOneRemark: '',
  zhTw: false,
  id: 0, // 初始值设为0，后续会被正确设置
})

// 编码规则对话框相关数据
const codeRuleDialogVisible = ref(false)
const codeRuleFormRef = ref<FormInstance>()
const codeRuleFormData = reactive({
  businessName: '工序维护',
  ruleName: '工艺管理',
  documentField: '工序编码',
  dateField: '注册时间',
  prefix: 'GY',
  ruleType: '年月日',
  numberLength: 5,
  incrementType: '编号每日从1开始自增',
  connector: ''
})

// 属性编码规则对话框相关数据
const attributeCodeRuleDialogVisible = ref(false)
const attributeCodeRuleFormRef = ref<FormInstance>()
const attributeCodeRuleFormData = reactive({
  businessName: '属性管理',
  ruleName: '属性编码',
  documentField: '属性编码',
  dateField: '创建时间',
  prefix: 'SC',
  ruleType: '年月日',
  numberLength: 5,
  incrementType: '编号每日从1开始自增',
  connector: ''
})

// 左侧搜索过滤后的数据
const filteredLeftTableData = computed(() => {
  if (!leftSearchKeyword.value) {
    return leftTableData.value
  }
  return leftTableData.value.filter((item: any) => 
    item.code.toLowerCase().includes(leftSearchKeyword.value.toLowerCase())
  )
})

// 右侧搜索过滤后的数据
const filteredRightTableData = computed(() => {
  if (!rightSearchKeyword.value) {
    return rightTableData.value
  }
  return rightTableData.value.filter((item: any) => 
    item.code.toLowerCase().includes(rightSearchKeyword.value.toLowerCase())
  )
})

// 加载左侧属性数据
const loadLeftAttributes = async (processId: number) => {
  try {
    console.log('开始加载左侧属性数据，processId:', processId)
    const res = await APIs.get('/api/Assignattributess/ShowAssignattributesOne', {
      params: {
        id: processId
      }
    })
    console.log('左侧接口返回数据:', res.data)
    
    const list = Array.isArray(res.data) ? res.data : (res.data?.data ?? [])
    console.log('解析后的左侧列表:', list)
    
    leftTableData.value = list.map((item: any) => ({
      id: item.assignattributesOneId ?? item.id ?? 0,
      code: item.AssignattributesOneEncode ?? item.assignattributesOneEncode ?? '',
      name: item.AssignattributesOneNamd ?? item.assignattributesOneNamd ?? '',
      remark: item.AssignattributesOneRemark ?? item.assignattributesOneRemark ?? ''
    }))
    
    console.log('映射后的左侧数据:', leftTableData.value)
  } catch (error) {
    console.error('加载左侧属性数据失败:', error)
    ElMessage.error('加载左侧属性数据失败')
    leftTableData.value = []
  }
}

// 加载右侧属性数据
const loadRightAttributes = async (processId: number) => {
  try {
    console.log('开始加载右侧属性数据，processId:', processId)
   
    const res = await APIs.get('/api/Assignattributess/ShowAssignattributesOneType', {
      params: {
        id: processId
      }
    })
    console.log('右侧接口返回数据:', res.data)
    
    const list = Array.isArray(res.data) ? res.data : (res.data?.data ?? [])
    console.log('解析后的右侧列表:', list)
    
    rightTableData.value = list.map((item: any) => ({
      id: item.assignattributesOneId ?? item.id ?? 0,
      value: item.assignattributesOneValue ?? item.assignattributesOnevalue ?? '',
      dataType: item.assignattributesOneType ?? item.assignattributesOneType ?? '',
      code: item.AssignattributesOneEncode ?? item.assignattributesOneEncode ?? '',
      name: item.AssignattributesOneNamd ?? item.assignattributesOneNamd ?? '',
      remark: item.AssignattributesOneRemark ?? item.assignattributesOneRemark ?? ''
    }))
    
    console.log('映射后的右侧数据:', rightTableData.value)
  } catch (error) {
    console.error('加载右侧属性数据失败:', error)
    ElMessage.error('加载右侧属性数据失败')
    rightTableData.value = []
  }
}

// 左侧选择变化处理
const handleLeftSelectionChange = (selection: any[]) => {
  leftSelectedRows.value = selection
  console.log('左侧选中项:', selection)
}

// 右侧选择变化处理
const handleRightSelectionChange = (selection: any[]) => {
  rightSelectedRows.value = selection
  console.log('右侧选中项:', selection)
}

// 右箭头按钮：将左侧选中项移动到右侧
const handleMoveToRight = async () => {
  if (leftSelectedRows.value.length === 0) {
    ElMessage.warning('请先选择左侧要操作的项目')
    return
  }

  try {
    console.log('开始移动左侧选中项到右侧')
    
    // 对每个选中项调用接口
    for (const item of leftSelectedRows.value) {
      const requestData = {
        assignattributesOneId: item.id
      }
      console.log('调用更新接口，参数:', requestData)
      
      const res = await APIs.post('/api/Assignattributess/UpdateAssignattributesOne', requestData)
      console.log('接口返回结果:', res.data)
    }
    
    ElMessage.success('操作成功')
    
    // 重新加载数据
    const selectedId = (selectedRows.value[0] as any).id
    loadLeftAttributes(selectedId)
    loadRightAttributes(selectedId)
    
    // 清空选择
    leftSelectedRows.value = []
    
  } catch (error) {
    console.error('移动操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 左箭头按钮：将右侧选中项移动到左侧
const handleMoveToLeft = async () => {
  if (rightSelectedRows.value.length === 0) {
    ElMessage.warning('请先选择右侧要操作的项目')
    return
  }

  try {
    console.log('开始移动右侧选中项到左侧')
    console.log('右侧选中的数据:', rightSelectedRows.value)
    
    // 对每个选中项调用新的接口
    for (const item of rightSelectedRows.value) {
      const requestData = {
        assignattributesOneId: item.id
      }
      console.log('调用 UpdateAssignattributeYou 接口，参数:', requestData)
      
      const res = await APIs.post('/api/Assignattributess/UpdateAssignattributeYou', requestData)
      console.log('接口返回结果:', res.data)
    }
    
    ElMessage.success('操作成功')
    
    // 重新加载数据
    const selectedId = (selectedRows.value[0] as any).id
    loadLeftAttributes(selectedId)
    loadRightAttributes(selectedId)
    
    // 清空选择
    rightSelectedRows.value = []
    
  } catch (error) {
    console.error('移动操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 表单数据
const formData = reactive<ProcessFormData>({
  processCode: '',
  processName: '',
  processType: '',
  workReportMode: '',
  description: ''
})

// 查询条件（与后端参数名保持一致）
const queryForm = reactive({
  processmaintenanceEncode: '',
  processmaintenanceName: '',
  processmaintenanceType: ''
})

// 表单验证规则
const formRules: FormRules = {
  processCode: [
    { required: true, message: '请输入工序编码', trigger: 'blur' }
  ],
  processName: [
    { required: true, message: '请输入工序名称', trigger: 'blur' }
  ],
  processType: [
    { required: true, message: '请选择工序类型', trigger: 'change' }
  ],
  workReportMode: [
    { required: true, message: '请选择报工模式', trigger: 'change' }
  ]
}

// 添加属性表单验证规则
const addAttributeFormRules: FormRules = {
  assignattributesOneEncode: [
    { required: true, message: '请输入属性编码', trigger: 'blur' }
  ],
  assignattributesOneNamd: [
    { required: true, message: '请输入属性名称', trigger: 'blur' }
  ]
}

// 编码规则表单验证规则
const codeRuleFormRules: FormRules = {
  businessName: [
    { required: true, message: '请选择业务名称', trigger: 'change' }
  ],
  ruleName: [
    { required: true, message: '请输入规则名称', trigger: 'blur' }
  ],
  documentField: [
    { required: true, message: '请选择单据字段', trigger: 'change' }
  ],
  prefix: [
    { required: true, message: '请输入前缀', trigger: 'blur' }
  ],
  ruleType: [
    { required: true, message: '请选择规则类型', trigger: 'change' }
  ],
  numberLength: [
    { required: true, message: '请输入编号位数', trigger: 'blur' }
  ]
}

// 属性编码规则表单验证规则
const attributeCodeRuleFormRules: FormRules = {
  businessName: [
    { required: true, message: '请选择业务名称', trigger: 'change' }
  ],
  ruleName: [
    { required: true, message: '请输入规则名称', trigger: 'blur' }
  ],
  documentField: [
    { required: true, message: '请选择单据字段', trigger: 'change' }
  ],
  prefix: [
    { required: true, message: '请输入前缀', trigger: 'blur' }
  ],
  ruleType: [
    { required: true, message: '请选择规则类型', trigger: 'change' }
  ],
  numberLength: [
    { required: true, message: '请输入编号位数', trigger: 'blur' }
  ]
}

// 工序维护数据改为从接口获取

// 分配属性数据处理已简化

// 获取类型标签颜色
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    '维修': 'info',
    '一般': 'info',
    '测试': 'warning',
    '锡膏': 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取报工模式标签颜色
const getModeTagType = (mode: string) => {
  const modeMap: Record<string, string> = {
    '状态': 'success',
    '数量': 'warning'
  }
  return modeMap[mode] || 'info'
}

// 生命周期
onMounted(() => {
  loadData()
})

// 加载数据（从后端接口获取） 
const loadData = async () => {
  try {
    const res = await APIs.get('/api/Processmaintenance/ShowProcessmaintenance', {
      params: {
        PageIndex: currentPage.value,
        PageSize: pageSize.value,
        ProcessmaintenanceEncode: queryForm.processmaintenanceEncode || undefined,
        ProcessmaintenanceName: queryForm.processmaintenanceName || undefined,
        ProcessmaintenanceType: queryForm.processmaintenanceType || undefined
      }
    })
    const list = Array.isArray(res.data) ? res.data : (res.data?.data ?? [])

    // 记录总数，用于分页显示（优先后端总数）
    total.value = (res.data?.totalCount ?? res.data?.total ?? list.length) || list.length

    // 计算序号（兼容后端未返回序号）
    const startIndex = (currentPage.value - 1) * pageSize.value
    tableData.value = list.map((item: any, index: number) => {
      // 适配后端字段到前端展示字段
      // 报工模式：后端整型(1/2) → 文本(数量/状态)，也兼容已是文本的情况
      const rawMode = (item.ProcessmaintenanceReportingmode ?? item.processmaintenanceReportingmode ?? item.workReportMode ?? item.processmaintenanceWorkReportMode)
      let workReportModeText = ''
      if (rawMode !== undefined && rawMode !== null) {
        if (typeof rawMode === 'number' || /^(\d+)$/.test(String(rawMode))) {
          const modeNum = Number(rawMode)
          workReportModeText = modeNum === 1 ? '数量' : modeNum === 2 ? '状态' : ''
        } else {
          workReportModeText = String(rawMode)
        }
      }
      const mapped: ProcessInfo = {
        id: item.id ?? item.processmaintenanceId ?? startIndex + index + 1,
        serialNumber: startIndex + index + 1,
        processCode: item.processmaintenanceEncode ?? item.processmaintenanceCode ?? item.processCode ?? '',
        processName: item.processmaintenanceName ?? item.processName ?? '',
        processType: item.processmaintenanceType ?? item.processType ?? '',
        workReportMode: workReportModeText,
        description: item.ProcessmaintenanceDescription ?? item.processmaintenanceDescription ?? item.processmaintenanceExplain ?? item.description ?? '',
        creator: item.processmaintenanceCreatorName ?? item.creator ?? '',
        createTime: item.ProcessmaintenanceCreatorTime ?? item.processmaintenanceCreatorTime ?? item.processmaintenanceCreateTime ?? item.createTime ?? '',
        updateTime: item.processmaintenanceUpdateTime ?? item.updateTime ?? '',
        
      }
      
      return mapped
    }) as ProcessInfo[]
  } catch (error) {
   
    ElMessage.error('加载数据失败')
  }
}

// 查询与重置
const handleQuery = () => {
  currentPage.value = 1
  loadData()
}

const handleReset = () => {
  queryForm.processmaintenanceEncode = ''
  queryForm.processmaintenanceName = ''
  queryForm.processmaintenanceType = ''
  currentPage.value = 1
  loadData()
}

// 切换查询条件显隐
const toggleSearch = () => {
  showSearch.value = !showSearch.value
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增工序'
  isEditMode.value = false
  editingId.value = null
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: ProcessInfo) => {
  dialogTitle.value = '编辑工序'
  isEditMode.value = true
  editingId.value = row.id
  // 将行数据映射到表单数据
  Object.assign(formData, {
    processCode: row.processCode,
    processName: row.processName,
    processType: row.processType,
    workReportMode: row.workReportMode,
    description: row.description
  })
  dialogVisible.value = true
}

// 删除
const handleDelete = (row: ProcessInfo) => {
  ElMessageBox.confirm(
    `确定要删除工序"${row.processName}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      console.log('删除工序:', row)
      
      // 调用删除接口
      const response = await APIs.post('/api/Processmaintenance/DeleteProcessmaintenance', {
        id: row.id
      })
      
      console.log('删除接口返回:', response.data)
      ElMessage.success('删除成功')
      loadData() // 刷新列表
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }).catch(() => {
    // 取消删除
    console.log('用户取消删除操作')
  })
}

// 导出
const handleExport = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要导出的数据')
    return
  }

  try {
    // 准备导出数据
    const exportData = selectedRows.value.map((row, index) => ({
      '序号': index + 1,
      '工序编码': row.processCode,
      '工序名称': row.processName,
      '工序类型': row.processType,
      '报工模式': row.workReportMode,
      '工序描述': row.description,
      '创建人': row.creator,
      '创建时间': row.createTime,
      '更新时间': row.updateTime
    }))

    // 创建工作簿
    const worksheet = (XLSX.utils as any).json_to_sheet(exportData)
    const workbook = (XLSX.utils as any).book_new()
    ;(XLSX.utils as any).book_append_sheet(workbook, worksheet, '工序维护')

    // 设置列宽
    const colWidths = [
      { wch: 8 },  // 序号
      { wch: 15 }, // 工序编码
      { wch: 20 }, // 工序名称
      { wch: 12 }, // 工序类型
      { wch: 12 }, // 报工模式
      { wch: 30 }, // 工序描述
      { wch: 12 }, // 创建人
      { wch: 20 }, // 创建时间
      { wch: 20 }  // 更新时间
    ]
    worksheet['!cols'] = colWidths

    // 生成Excel文件
    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' })
    const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    
    // 生成文件名（包含当前时间）
    const now = new Date()
    const timestamp = now.getFullYear() + 
      String(now.getMonth() + 1).padStart(2, '0') + 
      String(now.getDate()).padStart(2, '0') + '_' +
      String(now.getHours()).padStart(2, '0') + 
      String(now.getMinutes()).padStart(2, '0') + 
      String(now.getSeconds()).padStart(2, '0')
    
    const filename = `工序维护_${timestamp}.xlsx`
    
    // 下载文件
    saveAs(data, filename)
    
    ElMessage.success(`成功导出 ${selectedRows.value.length} 条数据`)
    console.log('导出数据:', exportData)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

// 分配属性
const handleAllocateAttributes = () => {
  if (selectedRows.value.length === 1) {
    const selectedId = (selectedRows.value[0] as any).id
    console.log('打开分配属性对话框，选中ID:', selectedId)
    
    // 清空搜索关键词
    leftSearchKeyword.value = ''
    rightSearchKeyword.value = ''
    
    // 同时加载左右两侧数据
    loadLeftAttributes(selectedId)
    loadRightAttributes(selectedId)
    
    allocateDialogVisible.value = true
  }
}

// 添加属性
const handleAddAttribute = () => {
  // 获取当前选中行的ID
  if (selectedRows.value.length !== 1) {
    ElMessage.warning('请先选择一条记录')
    return
  }
  
  const selectedRow = selectedRows.value[0] as any
  const selectedId = selectedRow.id
  console.log('添加属性，选中行完整数据:', selectedRow)
  console.log('添加属性，选中ID:', selectedId)
  console.log('选中行的所有字段:', Object.keys(selectedRow))
  
  // 先重置表单，然后设置工序ID
  resetAddAttributeForm()
  // 设置表单中的ID
  addAttributeFormData.id = selectedId
  console.log('设置表单ID后的值:', addAttributeFormData.id)
  console.log('完整表单数据:', addAttributeFormData)
  addAttributeDialogVisible.value = true
}

// 重置添加属性表单
const resetAddAttributeForm = () => {
  // 保存当前ID，重置其他字段
  const currentId = addAttributeFormData.id
  Object.assign(addAttributeFormData, {
    assignattributesOnevalue: '',
    assignattributesOneEncode: '',
    assignattributesOneNamd: '',
    assignattributesOneRemark: '',
    zhTw: false,
    id: currentId  // 保持当前ID不变
  })
  addAttributeFormRef.value?.clearValidate()
}

// 添加属性对话框关闭处理
const handleAddAttributeDialogClose = () => {
  resetAddAttributeForm()
}
//选择变化
// 提交添加属性
const handleAddAttributeSubmit = async () => {
  if (!addAttributeFormRef.value) return
  
  try {
    await addAttributeFormRef.value.validate()
    // 验证ID不为空或0
    if (!addAttributeFormData.id || addAttributeFormData.id === 0) {
      ElMessage.error('工序ID无效，请重新选择记录')
      console.error('ID验证失败:', addAttributeFormData.id)
      return
    }

    // 准备发送到接口的完整数据 - 根据Swagger文档，使用id字段
    const requestData = {
      assignattributesOnevalue: addAttributeFormData.assignattributesOnevalue || '',
      assignattributesOneEncode: addAttributeFormData.assignattributesOneEncode || '',
      assignattributesOneNamd: addAttributeFormData.assignattributesOneNamd || '',
      assignattributesOneRemark: addAttributeFormData.assignattributesOneRemark || '',
      zt: addAttributeFormData.zhTw || false,
      id: Number(addAttributeFormData.id)  // 根据Swagger文档，后端期望的就是id字段
    }
    
    console.log('提交添加属性请求，数据:', requestData)
    console.log('请求中的id值:', requestData.id, '类型:', typeof requestData.id)
    
    // 调用添加属性接口
    const response = await APIs.post('/api/Assignattributess/AddAssignattributesOne', requestData)
    
    console.log('添加属性接口返回:', response.data)
    ElMessage.success('添加属性成功')
    addAttributeDialogVisible.value = false
    
    // 刷新分配属性页面的左右两侧数据
    if (selectedRows.value.length === 1) {
      const selectedId = (selectedRows.value[0] as any).id
      console.log('刷新分配属性页面，工序ID:', selectedId)
      // 重新加载左侧可用属性和右侧已分配属性
      await loadLeftAttributes(selectedId)
      await loadRightAttributes(selectedId)
    }
  } catch (error) {
    console.error('添加属性失败:', error)
    console.log('错误详情:', error)
    ElMessage.error('添加属性失败，请重试')
  }
}
// 分配属性对话框关闭
const handleAllocateDialogClose = () => {
  allocateDialogVisible.value = false
}

// 分配属性确认
const handleAllocateConfirm = async () => {
  try {
    console.log('点击确定按钮，开始保存右侧列表数据')
    console.log('右侧表格数据:', rightTableData.value)
    
    // 遍历右侧所有数据，保存每一条的文本框值
    for (const item of rightTableData.value) {
      const requestData = {
        assignattributesOneId: (item as any).id,
        assignattributesOnevalue: (item as any).value || '' // 文本框的值
      }
      console.log('保存数据，参数:', requestData)
      
      const res = await APIs.post('/api/Assignattributess/UpdateAssignattributeFangfaOne', requestData)
      console.log('保存结果:', res.data)
    }
    
    ElMessage.success('保存成功')
    
    // 关闭对话框
    allocateDialogVisible.value = false
    
    // 刷新主页面数据
    loadData()
    
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 选择变化
const handleSelectionChange = (selection: ProcessInfo[]) => {
  selectedRows.value = selection
  // 只有选择1项时才启用分配属性按钮
  isAllocateBtnDisabled.value = selection.length !== 1
  
 
}



// 分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  loadData()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadData()
}

// 跳转页面
const handleJumpPage = () => {
  const page = parseInt(jumpPage.value)
  if (page && page > 0 && page <= Math.ceil(total.value / pageSize.value)) {
    currentPage.value = page
    loadData()
  } else {
    ElMessage.warning('请输入有效的页码')
  }
}

// 对话框关闭
const handleDialogClose = () => {
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    processCode: '',
    processName: '',
    processType: '',
    workReportMode: '',
    description: ''
  })
  formRef.value?.clearValidate()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 准备提交数据，映射到后端接口字段
    const submitData = {
      processmaintenanceEncode: formData.processCode,
      processmaintenanceName: formData.processName,
      processmaintenanceType: formData.processType,
      processmaintenanceReportingmode: formData.workReportMode === '数量' ? 1 : 2, // 数量=1, 状态=2
      processmaintenanceDescription: formData.description
    }
    
    console.log('提交数据:', submitData)
    console.log('编辑模式:', isEditMode.value, '编辑ID:', editingId.value)
    
    let response
    if (isEditMode.value && editingId.value) {
      // 编辑模式：调用更新接口，需要包含ID
      const updateData = {
        ...submitData,
        id: editingId.value
      }
      response = await APIs.post('/api/Processmaintenance/UpdateProcessmaintenance', updateData)
      console.log('更新接口返回:', response.data)
      ElMessage.success('修改成功')
    } else {
      // 新增模式：调用添加接口
      response = await APIs.post('/api/Processmaintenance/AddProcessmaintenance', submitData)
      console.log('添加接口返回:', response.data)
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
    loadData() // 刷新列表
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(isEditMode.value ? '修改失败，请重试' : '添加失败，请重试')
  }
}

// 编码规则相关方法
const handleCodeClick = () => {
  codeRuleDialogVisible.value = true
}

const handleCodeRuleDialogClose = () => {
  resetCodeRuleForm()
}

const handleCodeRuleCancel = () => {
  codeRuleDialogVisible.value = false
  resetCodeRuleForm()
}

const resetCodeRuleForm = () => {
  Object.assign(codeRuleFormData, {
    businessName: '工序维护',
    ruleName: '工艺管理',
    documentField: '工序编码',
    dateField: '注册时间',
    prefix: 'GY',
    ruleType: '年月日',
    numberLength: 5,
    incrementType: '编号每日从1开始自增',
    connector: ''
  })
  codeRuleFormRef.value?.clearValidate()
}

const generatePreviewCode = () => {
  const { prefix, ruleType, numberLength, connector } = codeRuleFormData
  const now = new Date()
  
  let datePart = ''
  switch (ruleType) {
    case '年':
      datePart = now.getFullYear().toString()
      break
    case '年月':
      datePart = now.getFullYear().toString() + 
        String(now.getMonth() + 1).padStart(2, '0')
      break
    case '年月日':
      datePart = now.getFullYear().toString() + 
        String(now.getMonth() + 1).padStart(2, '0') + 
        String(now.getDate()).padStart(2, '0')
      break
    case '无':
      datePart = ''
      break
  }
  
  const numberPart = '1'.padStart(numberLength, '0')
  
  let code = prefix || ''
  if (datePart && code) {
    code += connector + datePart
  } else if (datePart) {
    code += datePart
  }
  
  if (numberPart && code) {
    code += connector + numberPart
  } else if (numberPart) {
    code += numberPart
  }
  
  return code || '预览编码'
}

// 生成真正的自增工序编码
const generateActualProcessCode = async () => {
  const { prefix, ruleType, numberLength, connector } = codeRuleFormData
  const now = new Date()
  
  let datePart = ''
  switch (ruleType) {
    case '年':
      datePart = now.getFullYear().toString()
      break
    case '年月':
      datePart = now.getFullYear().toString() + 
        String(now.getMonth() + 1).padStart(2, '0')
      break
    case '年月日':
      datePart = now.getFullYear().toString() + 
        String(now.getMonth() + 1).padStart(2, '0') + 
        String(now.getDate()).padStart(2, '0')
      break
    case '无':
      datePart = ''
      break
  }
  
  // 构造前缀部分（不包含序号）
  let codePrefix = prefix || ''
  if (datePart) {
    if (codePrefix && connector) {
      codePrefix += connector + datePart
    } else if (codePrefix) {
      codePrefix += datePart
    } else {
      codePrefix = datePart
    }
  }
  
  try {
    // 查询现有的工序编码，找到最大的序号
    let maxNumber = 0
    
    // 遍历现有数据查找最大序号
    for (const item of tableData.value) {
      const processCode = item.processCode || ''
      
      // 构建匹配模式，用于检查是否符合当前编码规则
      const expectedPrefix = codePrefix
      
      // 检查是否以当前前缀开头
      if (processCode.startsWith(expectedPrefix)) {
        // 提取序号部分
        let numberPart = ''
        
        if (connector && codePrefix) {
          // 如果有连接符，序号在最后一个连接符之后
          const lastConnectorIndex = processCode.lastIndexOf(connector)
          if (lastConnectorIndex !== -1) {
            numberPart = processCode.substring(lastConnectorIndex + connector.length)
          }
        } else {
          // 如果没有连接符，序号就是前缀之后的部分
          numberPart = processCode.substring(expectedPrefix.length)
        }
        
        // 尝试解析为数字
        const currentNumber = parseInt(numberPart, 10)
        if (!isNaN(currentNumber) && currentNumber > maxNumber) {
          maxNumber = currentNumber
        }
      }
    }
    
    // 下一个序号
    const nextNumber = maxNumber + 1
    const numberPart = nextNumber.toString().padStart(numberLength, '0')
    
    // 拼接最终编号
    if (codePrefix && connector) {
      return codePrefix + connector + numberPart
    } else {
      return codePrefix + numberPart
    }
    
  } catch (error) {
    console.error('生成工序编码失败:', error)
    // 如果出错，返回默认编号
    const numberPart = '1'.padStart(numberLength, '0')
    if (codePrefix && connector) {
      return codePrefix + connector + numberPart
    } else {
      return codePrefix + numberPart
    }
  }
}

const handleCodeRuleSave = async () => {
  if (!codeRuleFormRef.value) return
  
  try {
    await codeRuleFormRef.value.validate()
    
    // 生成真正的自增编码
    const generatedCode = await generateActualProcessCode()
    formData.processCode = generatedCode
    
    ElMessage.success('工序编码已生成: ' + generatedCode)
    codeRuleDialogVisible.value = false
  } catch (error) {
    console.error('保存编码规则失败:', error)
    ElMessage.error('请检查表单输入')
  }
}

// 属性编码规则相关方法
const handleAttributeCodeClick = () => {
  attributeCodeRuleDialogVisible.value = true
}

const handleAttributeCodeRuleDialogClose = () => {
  resetAttributeCodeRuleForm()
}

const handleAttributeCodeRuleCancel = () => {
  attributeCodeRuleDialogVisible.value = false
  resetAttributeCodeRuleForm()
}

const resetAttributeCodeRuleForm = () => {
  Object.assign(attributeCodeRuleFormData, {
    businessName: '属性管理',
    ruleName: '属性编码',
    documentField: '属性编码',
    dateField: '创建时间',
    prefix: 'SC',
    ruleType: '年月日',
    numberLength: 5,
    incrementType: '编号每日从1开始自增',
    connector: ''
  })
  attributeCodeRuleFormRef.value?.clearValidate()
}

const generateAttributePreviewCode = () => {
  const { prefix, ruleType, numberLength, connector } = attributeCodeRuleFormData
  const now = new Date()
  
  let datePart = ''
  switch (ruleType) {
    case '年':
      datePart = now.getFullYear().toString()
      break
    case '年月':
      datePart = now.getFullYear().toString() + 
        String(now.getMonth() + 1).padStart(2, '0')
      break
    case '年月日':
      datePart = now.getFullYear().toString() + 
        String(now.getMonth() + 1).padStart(2, '0') + 
        String(now.getDate()).padStart(2, '0')
      break
    case '无':
      datePart = ''
      break
  }
  
  const numberPart = '1'.padStart(numberLength, '0')
  
  let code = prefix || ''
  if (datePart && code) {
    code += connector + datePart
  } else if (datePart) {
    code += datePart
  }
  
  if (numberPart && code) {
    code += connector + numberPart
  } else if (numberPart) {
    code += numberPart
  }
  
  return code || '预览编码'
}

// 生成真正的自增属性编码
const generateActualAttributeCode = async () => {
  const { prefix, ruleType, numberLength, connector } = attributeCodeRuleFormData
  const now = new Date()
  
  let datePart = ''
  switch (ruleType) {
    case '年':
      datePart = now.getFullYear().toString()
      break
    case '年月':
      datePart = now.getFullYear().toString() + 
        String(now.getMonth() + 1).padStart(2, '0')
      break
    case '年月日':
      datePart = now.getFullYear().toString() + 
        String(now.getMonth() + 1).padStart(2, '0') + 
        String(now.getDate()).padStart(2, '0')
      break
    case '无':
      datePart = ''
      break
  }
  
  // 构造前缀部分（不包含序号）
  let codePrefix = prefix || ''
  if (datePart) {
    if (codePrefix && connector) {
      codePrefix += connector + datePart
    } else if (codePrefix) {
      codePrefix += datePart
    } else {
      codePrefix = datePart
    }
  }
  
  try {
    // 查询现有的属性编码，找到最大的序号
    let maxNumber = 0
    
    // 遍历现有的左侧和右侧属性数据查找最大序号
    const allAttributeCodes = [
      ...leftTableData.value.map((item: any) => item.code || ''),
      ...rightTableData.value.map((item: any) => item.code || '')
    ]
    
    for (const attributeCode of allAttributeCodes) {
      // 构建匹配模式，用于检查是否符合当前编码规则
      const expectedPrefix = codePrefix
      
      // 检查是否以当前前缀开头
      if (attributeCode.startsWith(expectedPrefix)) {
        // 提取序号部分
        let numberPart = ''
        
        if (connector && codePrefix) {
          // 如果有连接符，序号在最后一个连接符之后
          const lastConnectorIndex = attributeCode.lastIndexOf(connector)
          if (lastConnectorIndex !== -1) {
            numberPart = attributeCode.substring(lastConnectorIndex + connector.length)
          }
        } else {
          // 如果没有连接符，序号就是前缀之后的部分
          numberPart = attributeCode.substring(expectedPrefix.length)
        }
        
        // 尝试解析为数字
        const currentNumber = parseInt(numberPart, 10)
        if (!isNaN(currentNumber) && currentNumber > maxNumber) {
          maxNumber = currentNumber
        }
      }
    }
    
    // 下一个序号
    const nextNumber = maxNumber + 1
    const numberPart = nextNumber.toString().padStart(numberLength, '0')
    
    // 拼接最终编号
    if (codePrefix && connector) {
      return codePrefix + connector + numberPart
    } else {
      return codePrefix + numberPart
    }
    
  } catch (error) {
    console.error('生成属性编码失败:', error)
    // 如果出错，返回默认编号
    const numberPart = '1'.padStart(numberLength, '0')
    if (codePrefix && connector) {
      return codePrefix + connector + numberPart
    } else {
      return codePrefix + numberPart
    }
  }
}

const handleAttributeCodeRuleSave = async () => {
  if (!attributeCodeRuleFormRef.value) return
  
  try {
    await attributeCodeRuleFormRef.value.validate()
    
    // 生成真正的自增属性编码
    const generatedCode = await generateActualAttributeCode()
    addAttributeFormData.assignattributesOneEncode = generatedCode
    
    ElMessage.success('属性编码已生成: ' + generatedCode)
    attributeCodeRuleDialogVisible.value = false
  } catch (error) {
    console.error('保存属性编码规则失败:', error)
    ElMessage.error('请检查表单输入')
  }
}
</script>

<style scoped>
.process-maintenance {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100%;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 列表工具栏样式，与表格同块 */
.list-toolbar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin: 0 0 10px 0;
}

.search-section {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.button-section {
  display: flex;
  gap: 10px;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow-x: auto;
}

/* 表格样式优化 */
/* 让表格自适应而非强制 100% 宽度，避免横向滚动条 */
.table-container :deep(.el-table__body-wrapper),
.table-container :deep(.el-table__header-wrapper) {
  overflow-x: hidden;
}

/* 让各列均分剩余空间并填满右侧空白 */
.table-container :deep(.el-table) {
  table-layout: fixed;
  width: 100%;
}

/* 单元格溢出省略显示 */
.table-container :deep(.el-table .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 优化列宽分配 */
.table-container :deep(.el-table__cell) {
  padding: 8px 12px;
}

/* 响应式表格 */
@media (max-width: 1200px) {
  .table-container {
    overflow-x: auto;
  }
  
  .table-container :deep(.el-table) {
    min-width: 1200px;
  }
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-left {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #606266;
  font-size: 14px;
}

.pagination-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.jump-input {
  width: 50px;
}

/* 图标按钮样式 */
.icon-btn {
  color: #606266;
  padding: 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.icon-btn:hover {
  color: #409eff;
  background: #f5f7fa;
}

/* 分配属性按钮样式 */
.allocate-btn {
  background: #f4f4f5;
  border-color: #d9d9d9;
  color: #606266;
}

.allocate-btn:hover {
  background: #e9e9eb;
  border-color: #c0c4cc;
  color: #409eff;
}

/* 搜索图标样式 */
.search-icon {
  margin-left: 5px;
  font-size: 12px;
  color: #c0c4cc;
}

.sort-icon {
  margin-left: 5px;
  font-size: 12px;
  color: #c0c4cc;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 分配属性对话框样式 */
.allocate-dialog-content {
  padding: 20px 0;
}

.transfer-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
  height: 400px;
}

.left-list,
.right-list {
  flex: 1;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.list-header {
  padding: 12px 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
  font-weight: 500;
  color: #606266;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  padding: 12px 16px;
  border-bottom: 1px solid #dcdfe6;
}

.table-wrapper {
  flex: 1;
  overflow: hidden;
}

.pagination-wrapper {
  padding: 12px 16px;
  border-top: 1px solid #dcdfe6;
  background: #f5f7fa;
  display: flex;
  justify-content: center;
}

.middle-buttons {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 16px;
  padding: 0 20px;
}

.middle-buttons .el-button {
  width: 40px;
  height: 40px;
}


/* 编码规则对话框样式 */
.clickable-input {
  cursor: pointer;
}

.clickable-input :deep(.el-input__inner) {
  cursor: pointer;
}

.code-icon {
  color: #909399;
  cursor: pointer;
}

.code-icon:hover {
  color: #409eff;
}

.rule-type-radio {
  width: 100%;
}

.code-preview-section {
  margin-top: 20px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.code-preview-section h4 {
  margin: 0 0 12px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.preview-code {
  font-size: 16px;
  color: #409eff;
  font-weight: 600;
  font-family: 'Courier New', monospace;
  padding: 8px 12px;
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 32px;
  line-height: 32px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .search-section {
    justify-content: center;
  }
  
  .button-section {
    justify-content: center;
  }
  
  .search-input {
    width: 100%;
  }
  
  .shuttle-container {
    flex-direction: column;
    height: auto;
  }
  
}
</style>
